using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLayersExample.Entity;
using NLayersExample.DataAccess.Interface;

namespace NLayersExample.DataAccess.Implementation
{
    public class DataAccessAccessPoint : IDataAccessAccessPoint
    {
        private DataModel _dbContext;

        public DataAccessAccessPoint()
        {
            _dbContext = new DataModel();
        }

        #region "Object Management"

        private Dictionary<Type, object> _instances = new Dictionary<Type, object>();

        private object GetSharedInstance<T1, T2>() where T2 : class
        {
            if (!_instances.ContainsKey(typeof(T1)))
            {
                _instances[typeof(T1)] = Activator.CreateInstance<T1>();

                (_instances[typeof(T1)] as BaseDA<T2>).EntityContext = _dbContext;
                (_instances[typeof(T1)] as BaseDA<T2>).DataAccess = this;
            }

            return _instances[typeof(T1)];
        }

        #endregion

        public void Refresh()
        {
            if (_dbContext.Connection.State != System.Data.ConnectionState.Open)
            {
                _dbContext.Connection.Open();

                if (_dbContext.Connection.State != System.Data.ConnectionState.Open)
                    _dbContext = new DataModel();
            }
        }

        public ISampleCustomerDA SampleCustomerDA
        {
            get { return GetSharedInstance<SampleCustomerDA, SampleCustomer>() as SampleCustomerDA; }
        }
    }
}